package com.example.servicelearn

import android.app.Service
import android.content.Intent
import android.os.*
import android.util.Log


class MessageService : Service() {

    private val TAG = MessageService::class.java.name

    private val messageHandler = MessageHandler()

    private val mMessage = Messenger(messageHandler)

    open inner class MessageHandler : Handler() {
        override fun handleMessage(msg: Message) {

            when (msg.what) {
                0x0001 -> {
                    Log.e(
                        TAG,
                        "receive msg from client: msg = [" + msg.data.getString(Constants.MSG_KEY) + "]"
                    )
                    val client = msg.replyTo
                    val replyMsg: Message =
                        Message.obtain(null, Constants.MSG_FROM_SERVICE)
                    val bundle = Bundle()
                    bundle.putString(Constants.MSG_KEY, "我已经收到你的消息，稍后回复你！")
                    replyMsg.data = bundle
                    try {
                        client.send(replyMsg)
                    } catch (e: RemoteException) {
                        e.printStackTrace()
                    }
                }
                else -> {
                    super.handleMessage(msg)
                }
            }

//            super.handleMessage(msg)
        }
    }

    override fun onBind(intent: Intent): IBinder {

        Log.e(TAG, "onBind=========================")
        return mMessage.binder
    }


    override fun onCreate() {
        super.onCreate()
        Log.e(TAG, "onCreate=========================")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.e(TAG, "onDestroy=========================")
    }

    override fun onRebind(intent: Intent?) {
        super.onRebind(intent)
        Log.e(TAG, "onRebind=========================")
    }

    override fun onStart(intent: Intent?, startId: Int) {
        super.onStart(intent, startId)
        Log.e(TAG, "onStart=========================")
    }

    override fun onUnbind(intent: Intent?): Boolean {
        Log.e(TAG, "onUnbind=========================")
        return super.onUnbind(intent)

    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.e(TAG, "onStartCommand=========================")
        return super.onStartCommand(intent, flags, startId)
    }

}